#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Copyright © 启明星辰 版权所有
# @Time    : 2024/5/24 11:01
# @Author  : 胡浩浩
# @File    : clear_docker.py
# @IDE     : PyCharm
# @description :
import docker
import jmespath
import ruamel.yaml


def read_yml(file_path, node=None):
    with open(file_path, "r", encoding="utf-8") as f:
        yaml = ruamel.yaml.YAML(typ='unsafe', pure=True)
        yaml.allow_duplicate_keys = True
        data = yaml.load(f)
    if node:
        return data[node]
    else:
        return data if data else []

def write_to_yml(file_path, data):
    # 顺序写入新的yml文件中,保证格式不混乱
    with open(file_path, "w", encoding="utf-8") as f:
        ruamel.yaml.round_trip_dump(data, f, default_flow_style=False, allow_unicode=True)

def clear_yaml(file_path):
    with open(file_path, "w", encoding="utf-8") as f:
        f.truncate()



docker_list=read_yml("data_containers_list.yml")
container_id_list = jmespath.search("@[*][0]", docker_list)
client = docker.from_env()
if container_id_list:
    for container_id in container_id_list:
        container = client.containers.get(container_id)
        container.stop()
        container.remove()

write_to_yml("data_containers_list.yml", [])
write_to_yml("data_containers_user_relations_list.yml", [])
clear_yaml("data_containers_use_history.yml")
